const express = require('express');
const getResult = require("../utils/getResult");
const public = require('../api/public');
const databasePublic = require("../utils/databasePublic");
const database = new databasePublic(); //获取数据库方法
const hex_md5 = require("md5");
const getToken = require("../utils/interceptor").getToken;
const Router = express.Router();

// Router.post('/getSystemTime', getToken, (req, result) => { //获取系统时间
Router.post('/getSystemTime', (req, result) => { //获取系统时间
  public.getSystemTime().then(getSystemTimeRes => {
    result.json(getResult.success({
      Result: getSystemTimeRes.data.Result
    }));
  })
});

Router.post('/login', async (req, result) => { //登录
  const findRes = await database.find({
    library: "admin",
    listName: "user",
    whereStr: { userName: req.body.userName },
  }).catch(err => {
    console.log(err, "登录");
  });
  if (findRes && findRes.length) { //用户存在
    if (findRes[0].password === req.body.password) { //校验密码
      findRes[0].token = hex_md5(findRes[0].userId + "," + new Date().getTime());
      const updateOneRes = await database.updateOne({ //更新token
        library: "admin",
        listName: "user",
        whereStr: { userName: req.body.userName },
        updateStr: findRes[0],
      }).catch(err => {
        console.log(err);
      });
      if (updateOneRes) { //存入成功返回
        result.json(getResult.success({ //返回
          Result: {
            userName: findRes[0].userName,
            userId: findRes[0].userId,
            token: findRes[0].token
          },
          msg: "登录成功"
        }));
      } else { //失败返回
        result.json(getResult.fail({
          msg: "登录失败请稍后再试",
        }));
      };
    } else {
      result.json(getResult.fail({
        msg: "密码不正确",
      }));
    };
  } else {//报错或未查到用户
    result.json(getResult.fail({
      msg: "该用户不存在",
    }));
  }
});

Router.post('/register', async (req, result) => { //注册
  var msg = "";
  req.body.password === "" && (msg = "请设置您的密码");
  req.body.userName === "" && (msg = "请输入您的用户名");
  //格式正确查找用户名是否存在，不正确返回错误原因
  if (msg) {
    getResult.fail({
      msg,
    })
    return
  };
  const findRes = await database.find({
    library: "admin",
    listName: "user",
    whereStr: { userName: req.body.userName },
  }).catch(err => {
    console.log(err)
    result.json(getResult.busy());
  });
  if (!findRes) return; //数据库报错
  if (findRes.length) {
    result.json(getResult.fail({
      msg: "该用户名已存在",
    }))
  } else {
    const insertOneRes = await database.insertOne({
      library: "admin",
      listName: "user",
      message: {
        userName: req.body.userName,
        password: req.body.password,
        userId: hex_md5(req.body.userName),//生成userId
      }
    });
    insertOneRes ? result.json(getResult.success({
      msg: "注册成功，请登录"
    })) : result.json(getResult.busy())
  }
});


module.exports = Router;